import asyncio
import websockets

import websockets


class WSServer:

    def __init__(self, host, port, handle):
        self.host = host
        self.port = port
        self.handle = handle

    async def start(self):
        self.server = await websockets.serve(self.handle, self.host, self.port)
        await self.server.wait_closed()

    def close(self):
        self.server.close()


async def handle(websocket, path):
    try:
        data = await websocket.recv()

    except websockets.exceptions.WebSocketException:
        # 客户端发送了错误的数据格式
        websocket.close()
        return
    print(data)
    websocket.settimeout(5)
    await websocket.send(data)


if __name__ == "__main__":
    server = WSServer("192.168.1.242", 5678, handle)
    server.start()
    # loop = asyncio.new_event_loop()
    # asyncio.set_event_loop(loop)
    # loop.run_until_complete(start_server)
    # loop.run_forever()
